package com.purchase.ml.service.common.impl;

import com.purchase.ml.entity.seq.SysSeq;
import com.purchase.ml.mapper.common.CommonSeqMapper;
import com.purchase.ml.service.common.CommonSeqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * Created by kyyang on 2021/1/17 17:06
 */
@Service
public class CommonSeqServiceImpl implements CommonSeqService {

    @Autowired
    private CommonSeqMapper commonSeqMapper;


    @Override
    public Long curSeq(String seqName) {
        SysSeq sysSeq = commonSeqMapper.curSysOrderSeq(seqName);
        if(sysSeq==null){
            return -999L;
        }
        return sysSeq.getCurrentVal();
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public synchronized Long nextSeq(String seqName) {
        commonSeqMapper.updateSysOrderSeq(seqName);
        return curSeq(seqName);
    }

    @Override
    public Long curSysOrderSeq(String seqName) {
        SysSeq sysSeq = commonSeqMapper.curSysOrderSeq(seqName);
        if(sysSeq==null){
            return -999L;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(sysSeq.getPrefix());
        Random random = new Random();
//        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        int rannum = (int) (random.nextDouble() * (999 - 100 + 1)) + 100;
        sb.append(rannum);
        sb.append(sysSeq.getCurrentVal());
        return Long.valueOf(sb.toString());
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public synchronized Long nextSysOrderSeq(String seqName) {
        commonSeqMapper.updateSysOrderSeq(seqName);
        return curSysOrderSeq(seqName);
    }

    @Override
    public Long curSysOrderSeqAnd2Random(String seqName) {
        commonSeqMapper.updateSysOrderSeq(seqName); //更新当前索引
        SysSeq sysSeq = commonSeqMapper.curSysOrderSeq(seqName);
        if(sysSeq==null){
            return -999L;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(sysSeq.getPrefix());
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99 - 10 + 1)) + 10;
        sb.append(rannum);
        sb.append(sysSeq.getCurrentVal());
        return Long.valueOf(sb.toString());
    }
}
